<template>
  <view class="bx-filter" v-if="tags&&tags.length>0">
    <view class="form-box">
      <view class="filter-item" v-for="(item,index) in tags">
        <text class="label">
          {{item.label}}:
        </text>
        <date-range-selector :service="service" :ref="'filter'+index" :cfg="item.more_config"
          v-if="item.inputType ==='BetweenDate'">
        </date-range-selector>
        <string-input :tag="item" :ref="'filter'+index" :local="setOptions[item.colName]||[]" class="string-input"
          v-else-if="item.inputType ==='string'||item.inputType=='fk'||item.inputType=='Enum'">
        </string-input>
      </view>
      <view class="button-box">
        <button class="button margin-right" @click="toFilter">查询
        </button>
        <button class="button light" @click="reset">重置</button>
      </view>
    </view>

  </view>
</template>

<script>
  /**
   * @description - 通用筛选组件
   * 类型：时间范围-BetweenDate 字符串 枚举 fk tree
   * @param {Object} - config 配置数据  
   */
  import dateRangeSelector from './comp/date-range-selector.vue'
  import stringInput from './comp/string-input.vue'
  export default {
    components: {
      dateRangeSelector,
      stringInput
    },
    props: {
      mainData: {
        type: Object
      },
      fieldInfo: {
        type: [Object, Array]
      },
      srvApp: {
        type: String
      },
      tags: {
        type: Array
      },
      service: {
        type: String
      }
    },
    computed: {
      setOptions() {
        return this.fieldInfo.reduce((res, cur) => {
          let options = cur['option_list_v2']
          if (Array.isArray(options) && options.length > 0) {
            options = options.map(item => {
              item.text = item.label
              return item
            })
          }
          res[cur.columns] = options;
          return res
        }, {}) || {}
      },
      theme() {
        return this.$store?.state?.app?.theme
      }
    },
    data() {
      return {
        range: ["2021-03-8", "2023-4-20"],
        showDatePicker: false,
        filterCols: [],
        model: {},
        subList: ['今天', '昨天', '本周', '本月'],
        curSub: -1
      }
    },
    methods: {
      showCalendar() {
        this.showDatePicker = true
      },
      change(e, col) {
        this.curSub = e
        let startDate = ''
        let endDate = ''
        if (this.subList[e] == '今天') {
          startDate = this.dayjs().format("YYYY-MM-DD")
          endDate = startDate
        } else if (this.subList[e] == '昨天') {
          startDate = this.dayjs().subtract(1, 'day').format("YYYY-MM-DD")
          endDate = startDate
        } else if (this.subList[e] == '本周') {
          startDate = this.dayjs().day(1).format("YYYY-MM-DD")
          endDate = this.dayjs().day(7).format("YYYY-MM-DD")
        } else if (this.subList[e] == '本月') {
          startDate = this.dayjs().startOf('month').format('YYYY-MM-DD')
          endDate = this.dayjs().endOf('month').format('YYYY-MM-DD')
        }
        this.model[col?.more_config?.colName] = [startDate, endDate]
      },
      confirm(e, col) {
        this.curSub = -1
        this.showDatePicker = false
        console.log(e, col);
        if (col?.more_config?.colName) {
          this.model[col?.more_config?.colName] = e
        }
        // this.model
      },
      maskClick(e) {
        console.log('maskClick事件:', e);
      },
      toFilter() {
        let data = {}
        let tabs = this.tags
        let relation_Conditions = {
          "relation": "AND",
          "data": []
        }

        let colData = {}
        let relation = {
          "relation": "OR",
          "data": []
        }

        for (let i = 0; i < tabs.length; i++) {
          relation.data = []
          let child_relation = {
            "relation": "AND",
            "data": []
          }
          let data = null
          colData = {
            "colName": "",
            "ruleType": "",
            "value": ""
          }



          const filterVal = this.$refs['filter' + i][0]?.getVal?.()
          debugger
          if (["BetweenDate"].includes(tabs[i].inputType) && filterVal) {
            // relation.relation = 'AND'
            data = {
              colName: tabs[i]._colName[0],
              ruleType: 'between',
              value: filterVal
            }
          } else if (filterVal) {
            if (Array.isArray(tabs[i]._colName) && tabs[i]._colName.length > 0) {
              data = {
                "relation": "OR",
                "data": []
              }
              tabs[i]._colName.forEach(colName => {
                if (tabs[i].inputType === 'Enum' && filterVal) {
                  let arr = filterVal.split(',')
                  if (Array.isArray(arr) && arr.length > 0) {
                    arr.forEach(val => {
                      data.data.push({
                        colName: colName,
                        ruleType: 'eq',
                        value: val
                      })
                    })
                    return
                  }
                }
                data.data.push({
                  colName: colName,
                  ruleType: tabs[i]?.more_config?.ruleType || 'like',
                  value: filterVal
                })
              })
            }
            // data = {
            //   colName: tabs[i]._colName[0],
            //   ruleType: 'in',
            //   value: filterVal
            // }
          }
          if (data) {
            // relation_Conditions.data = relation.data
            relation_Conditions.data.push(this.deepClone(data))
          }
        }
        this.$emit('on-filter', relation_Conditions)
      },
      cancel() {
        this.$emit('cancel')
      },
      buildConditions(returnVal = false, filterTagsCfg) {
        let self = this
        let condsModel = self.formModel
        return
        const tagsRelationCondition = filterTagsCfg?.tag_select_relation
        console.log(filterTagsCfg);
        let relation_Conditions = {
          "relation": "AND",
          "data": []
        }

        const globalData = {
          ...this.globalVariable,
          data: {}
        }

        Object.keys(this.formModel).map(key => {
          if (Array.isArray(this.formModel[key].colName) && this.formModel[key].colName.length > 0) {
            globalData.data[this.formModel[key].colName[0]] = this.formModel[key].value
          }
        })

        let tabs = Object.keys(condsModel)

        let colData = {}
        let relation = {
          "relation": "OR",
          "data": []
        }

        for (let i = 0; i < tabs.length; i++) {
          relation.data = []
          let child_relation = {
            "relation": "AND",
            "data": []
          }

          colData = {
            "colName": "",
            "ruleType": "",
            "value": ""
          }
          if (['checkbox', 'radio', 'tree', 'fk'].includes(condsModel[tabs[i]].formType) && condsModel[tabs[i]].value &&
            condsModel[tabs[i]].value.length !== 0 && condsModel[tabs[i]].value !== '_unlimited_' && condsModel[tabs[i]]
            .value[0] !== '_unlimited_') {
            if (condsModel[tabs[i]].inputType === 'BetweenNumber' || condsModel[tabs[i]].inputType === 'Date' ||
              condsModel[tabs[i]].inputType === 'DateTime') {
              relation.relation = 'AND'
              relation.data = []
              let values = condsModel[tabs[i]].inputType === 'Date' || condsModel[tabs[i]].inputType === 'DateTime' ?
                self.formatDateValues(condsModel[tabs[i]].value) : condsModel[tabs[i]].value

              for (let v = 0; v < values.length; v++) {
                child_relation = {
                  "relation": "AND",
                  "data": []
                }

                let betval = values[v].split(",")
                for (let j = 0; j < betval.length; j++) {
                  colData = {
                    "colName": "",
                    "ruleType": "",
                    "value": ""
                  }
                  if (betval[j] !== '-') {
                    if (j === 0 && betval[j] !== '-') {
                      colData.colName = condsModel[tabs[i]].colName[0]
                      colData.value = condsModel[tabs[i]].inputType === 'Date' || condsModel[tabs[i]].inputType ===
                        'DateTime' ? betval[j] : Number(betval[j])
                      colData.ruleType = betval.length > 1 ? "ge" : "like" // 只有一个只时候 按照 like 查询

                    } else if (betval[j] !== '-') {
                      colData.colName = condsModel[tabs[i]].colName[0]
                      colData.value = condsModel[tabs[i]].inputType === 'Date' || condsModel[tabs[i]].inputType ===
                        'DateTime' ? betval[j] : Number(betval[j])
                      colData.ruleType = "le"
                    }
                    if (values.length > 1) {
                      child_relation.data.push(self.deepClone(colData))
                    } else {
                      relation.data.push(self.deepClone(colData))
                    }
                  }
                }

                if (values.length > 1) {
                  relation.relation = 'OR' // 大于1个选项时处理 OR
                  relation.data.push(self.deepClone(child_relation))
                }
              }
            } else if (['Enum', 'Dict', 'group'].includes(condsModel[tabs[i]].inputType)) {
              let value = ''
              if (['tree', 'radio', 'fk'].includes(condsModel[tabs[i]].formType)) {
                value = condsModel[tabs[i]].value
              } else if (Array.isArray(condsModel[tabs[i]].value) && condsModel[tabs[i]].value.length > 0) {
                value = condsModel[tabs[i]].value.join(",")
              }
              relation.relation = 'OR'
              colData.colName = condsModel[tabs[i]].colName[0]
              colData.value = value

              // colData.ruleType = "in"
              if (value && value.indexOf(',') !== -1) {
                colData.ruleType = "in"
              } else {
                colData.ruleType = "like"
              }
              if (tagsRelationCondition && tagsRelationCondition[colData.colName]?.relation) {
                console.log(globalData);
                let relationCondition = this.deepClone(tagsRelationCondition[colData.colName])
                relationCondition = this.buildRelationCondition(tagsRelationCondition[colData.colName], globalData)
                if (relationCondition?.relation) {
                  // colData = relationCondition
                  relation_Conditions.data = [relationCondition]
                }
              } else {
                relation.data.push(self.deepClone(colData))
              }

              // relation_Conditions.data.push(self.deepClone(colData))
            } else if (condsModel[tabs[i]].inputType === 'String') {
              let tags = condsModel[tabs[i]].tags
              // let rt = 
              let val = condsModel[tabs[i]].value
              if (typeof val === 'string') {
                val = val.split(',')
              }
              if (Array.isArray(val)) {
                for (let j = 0; j < val.length; j++) {
                  let rt = tags.find((item) => {
                    if (item.value === val[j]) {
                      return true
                    }
                  })
                  relation.relation = 'OR'
                  colData.colName = condsModel[tabs[i]].colName[0]
                  colData.ruleType = rt?.ruleType || 'like'
                  colData.value = rt?.value || ''
                  relation.data.push(self.deepClone(colData))
                }
              }
            }

          } else if (condsModel[tabs[i]].formType === 'input' && condsModel[tabs[i]].value && condsModel[tabs[i]].value
            .length !== 0) {
            child_relation = {
              "relation": "OR",
              "data": []
            }
            console.log(condsModel[tabs[i]].colName);
            for (let col = 0; col < condsModel[tabs[i]].colName.length; col++) {
              colData.colName = condsModel[tabs[i]].colName[col]
              colData.value = condsModel[tabs[i]].value
              if (self.inputMoreConfig.value !== '') {
                colData.ruleType = self.inputMoreConfig.value
              } else {
                colData.ruleType = "[like]"
              }
              relation.data.push(self.deepClone(colData))
            }
          } else if (!condsModel[tabs[i]].value) {
            console.log(condsModel[tabs[i]]);
            if (Array.isArray(relation_Conditions?.data) && relation_Conditions.data.length > 0 && Array.isArray(
                filterTagsCfg?.strictTags) && filterTagsCfg?.strictTags.length > 1) {
              // 严格匹配模式
              const colName = condsModel[tabs[i]].colName[0]
              if (filterTagsCfg?.strictTags.indexOf(colName) !== -1) {
                // relation_Conditions.data.push({
                //   colName,
                //   ruleType: 'isnull',
                //   value: ''
                // })
              }

            }
          }

          if (relation.data.length !== 0) {
            relation_Conditions.data.push(self.deepClone(relation))
          }
        }

        if (returnVal == true) {
          return {
            relation_condition: relation_Conditions,
            value: this.formModel?. [this.tabs?. [this.curTag]?.list_tab_no]?.value
          }
        }
        return relation_Conditions

      },
      reset() {
        let tabs = this.tags
        if (Array.isArray(tabs) && tabs.length > 0) {
          for (let i = 0; i < tabs.length; i++) {
            this.$refs['filter' + i][0]?.reset?.()
          }
          this.$emit('on-filter', null)
          this.filterCols = this.fieldInfo
        }
        return
      }
    },
    mounted() {
      this.reset()
    }
  }
</script>

<style scoped lang="scss">
  .bx-filter {
    display: flex;
    flex-direction: column;
    // border-radius: 30rpx 30rpx 0 0;

    .view {
      flex: 1;
    }

    .form-box {
      display: flex;
      flex-wrap: wrap;

      .filter-item {
        display: flex;
        align-items: center;
        margin-bottom: 1rem;

        &-box {
          display: flex;
          align-items: center;
          border: 1px solid #f1f1f1;
          padding: 1rem 2rem;
          border-radius: 1rem;
          min-width: 40rem;
          justify-content: center;
        }

        .separator {
          width: 5rem;
          text-align: center;
        }

        .label {
          margin-right: 1rem;
          min-width: 12rem;
          padding: 1rem;
          text-align: right;
        }

        .string-input {
          // flex: 1;
          width: 25rem;
          min-width: 20rem;
        }
      }

      .tip {
        height: 300rpx;
        line-height: 300rpx;
        text-align: center;
      }
    }

    .button-box {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin: 0;
      // box-shadow: 6px 5px 13px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      padding: 1rem;
      // width: 100%;

      .cu-btn {
        // flex: 1;
        width: 200rpx;
        border-radius: 20px;

        &+.cu-btn {
          // margin-left: 20rpx;
        }

        &.confirm {
          // flex: 2;
        }
      }
    }

  }
</style>
